package cn.highedu.coolshark.account.controller;

import cn.highedu.coolshark.account.pojo.dto.AdminLoginInfoDTO;
import cn.highedu.coolshark.account.pojo.vo.AdminLoginInfoVO;
import cn.highedu.coolshark.account.pojo.vo.AdminStandardVO;
import cn.highedu.coolshark.account.pojo.vo.JwtVO;
import cn.highedu.coolshark.account.security.UserDetailsImpl;
import cn.highedu.coolshark.account.service.IAdminService;
import cn.highedu.coolshark.common.JsonResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

/**
 * 处理认证相关请求的控制器
 */
@RequestMapping("/auth")
@RestController
@Slf4j
public class AuthController {

    @Autowired
    private IAdminService adminService;

    /**
     * 处理登录请求
     */
    @PostMapping("/login")
    public JsonResult<JwtVO> login(@RequestBody AdminLoginInfoDTO adminLoginInfoDTO,
                                   @RequestHeader(name = "X-Real-IP",defaultValue = "0.0.0.0") String ip,
                                   @RequestHeader(name = "User-Agent", defaultValue = "未知") String ua) {
        log.debug("开始处理【管理员登录】的请求，参数：{}", adminLoginInfoDTO);
        JwtVO token = adminService.login(adminLoginInfoDTO);
        return JsonResult.ok(token);
    }

    /**
     * 获取当前登录的管理员信息
     * @param userDetails 从Token中解析出来的管理员信息，来自SecurityContextHolder
     *                    通过@AuthenticationPrincipal注解，将UserDetailsImpl对象注入到方法参数中
     * @return 当前登录的管理员信息
     */
    @GetMapping("/info")
    public JsonResult<AdminStandardVO> getInfo(
            @AuthenticationPrincipal UserDetailsImpl userDetails) {
        log.debug("开始处理【根据token查询管理员信息】的请求，参数：{}", userDetails);
        AdminLoginInfoVO adminLoginInfoVO = userDetails.getAdmin();
        AdminStandardVO admin = adminService.getAdminById(adminLoginInfoVO.getId());
        log.debug("管理员信息：{}", admin);
        return JsonResult.ok(admin);
    }

    /**
     * 登出操作，将登出的Token存储到黑名单
     */
    @PostMapping("/logout")
    public JsonResult<Void> logout(@RequestHeader("Authorization") String token) {
        log.debug("开始处理【登出操作】的请求，token：{}", token);
        adminService.logout(token);
        return JsonResult.ok();
    }
}
